package com.servlet;
import com.dao.impl.FruitDAOImpl;
import com.dao.uitil.JDBCUtil;
import com.pojo.Friut;
import org.junit.Test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;

public class AddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //get方式目前不需要设置编码（基于tomcat8）
        /*
           //如果是get请求发送的中文数据，转码稍微有点麻烦（tomcat8之前）
        String fname = req.getParameter("fname");
        //1、将字符串打散成字节数组
        byte[] bytes = fname.getBytes("ISO-8859-1");
        //2、将字节数组按照设定的编码重新组装字符串
        fname = new String(bytes,"UTF-8");
        */

        //post方式下，设置编码，防止中文乱码
        req.setCharacterEncoding("UTF-8");
        //需要注意的是，设置编码这一句话必须在所有的获取参数之前
        String fname = req.getParameter("fname");
        String priceStr = req.getParameter("price");
        int price = Integer.parseInt(priceStr);

        String fcountStr = req.getParameter("fcount");
        int fcount = Integer.parseInt(fcountStr);
        String remark = req.getParameter("remark");


        FruitDAOImpl dao = new FruitDAOImpl();
        Connection conn = null;
        try {
            conn = JDBCUtil.getConnection();
            Friut friut = new Friut(fname,price,fcount,remark);
            dao.insert(conn,friut);
            System.out.println("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.closeResource(conn,null);
        }



//        System.out.println("fname = " + fname);
//        System.out.println("price = " + price);
//        System.out.println("fcount = " + fcount);
//        System.out.println("remark = " + remark);

    }
//    @Test
//    public void test(){
//        FruitDAOImpl dao = new FruitDAOImpl();
//        Connection conn = null;
//        try {
//            conn = JDBCUtil.getConnection();
//            Friut friut = new Friut();
//            dao.insert(conn,friut);
//            System.out.println("添加成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            JDBCUtil.closeResource(conn,null);
//        }
//    }
}
